#include "stdafx.h"
#include "BatchedQuad.h"

using namespace MomogenkyouSystem;

#define		MAXQUADS	4096

INDEXBUFFER		BatchedQuad::g_IndexBuffer(NULL);

BatchedQuad::BatchedQuad()
:	m_VertexBuffer(NULL),
	m_pVertexMemory(NULL),
	m_iCurrentCount(0)
{
}

BatchedQuad::~BatchedQuad()
{
	m_pVertexMemory = NULL;
}

void	BatchedQuad::PrepareIndexBuffer()
{
	HRESULT _Result = S_OK;
	_Result = GraphicsSystem::Device->CreateIndexBuffer(MAXQUADS * sizeof(short) * 6, D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &g_IndexBuffer, NULL);
	ASSERT(_Result == S_OK, "Unable to create VertexBuffer for BatchedQuad");

	short * _Indices = NULL;

	g_IndexBuffer->Lock(0, 0, (void **)&_Indices, 0);
	for (short i = 0, j = 0; i < MAXQUADS * 6; i += 6, j += 4)
	{
		_Indices[i + 0]	= j;
		_Indices[i + 1]	= j + 1;
		_Indices[i + 2]	= j + 2;
		_Indices[i + 3]	= j + 2;
		_Indices[i + 4]	= j + 3;
		_Indices[i + 5]	= j;
	}
	g_IndexBuffer->Unlock();
}

void	BatchedQuad::ReleaseIndexBuffer()
{
	g_IndexBuffer->Release();
}

void	BatchedQuad::PrepareRender()
{
	GraphicsSystem::Device->SetIndices(g_IndexBuffer);
	GraphicsSystem::Device->SetFVF(Vertex::FVF);
	GraphicsSystem::Device->SetVertexDeclaration(Vertex::Declaration());
}

void	BatchedQuad::Initialize()
{
	HRESULT _Result = S_OK;

	_Result = GraphicsSystem::Device->CreateVertexBuffer(MAXQUADS * sizeof(Vertex) * 4, D3DUSAGE_WRITEONLY, Vertex::FVF, D3DPOOL_MANAGED, &m_VertexBuffer, NULL);
	ASSERT(_Result == S_OK, "Unable to create VertexBuffer for BatchedQuad");
}

void	BatchedQuad::Shutdown()
{
	m_VertexBuffer->Release();
}

void	BatchedQuad::Lock()
{
	HRESULT _Result = S_OK;
	_Result = m_VertexBuffer->Lock(0, 0, (void **)&m_pVertexMemory, 0);
	ASSERT(_Result == S_OK, "Unable to lock VertexBuffer for BatchedQuad");
}


void	BatchedQuad::Unlock()
{
	HRESULT _Result = S_OK;
	_Result = m_VertexBuffer->Unlock();
	ASSERT(_Result == S_OK, "Unable to unlock VertexBuffer for BatchedQuad");
}

void	BatchedQuad::Feed(	const	void	*	pData,
							const	size_t		iDataCount)
{
	
	memcpy(&m_pVertexMemory[m_iCurrentCount], (Vertex *)pData, iDataCount);
	m_iCurrentCount += iDataCount;
}

void	BatchedQuad::Render()
{
	ASSERT(m_iCurrentCount >> 1 < MAXQUADS, "Exceeded max batchquads");

	//	Call this externally using PrepareRender to prevent multiple calls
	//	GraphicsSystem::Device->SetIndices(g_IndexBuffer);
	//	GraphicsSystem::Device->SetFVF(Vertex::FVF);
	//	GraphicsSystem::Device->SetVertexDeclaration(Vertex::Declaration());

	GraphicsSystem::Device->SetStreamSource(0, m_VertexBuffer, 0, 0);
	GraphicsSystem::Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_iCurrentCount, 0, m_iCurrentCount >> 1);
	m_iCurrentCount = 0;
}